/**
 * 说明： 是一个按钮类自定义控件的示例
 * */
(function (factory) {
    var nameSpace = 'field_12671202405311102';
    if (!window[nameSpace]) {
        var Builder = factory();
        window[nameSpace] = {
            instance: {}
        };
        window[nameSpace].init = function (options) {
            window[nameSpace].instance[options.privateId] = new Builder(options);
        };
        window[nameSpace].isNotNull = function (obj) {
            return true;
        };
    }
})(function () {
    /**
     * 构造函数
     * @param options
     * @constructor
     */
    function App(options) {
        var self = this;
        //初始化参数
        self.initParams(options);
        //初始化dom
        self.initDom();
        //事件
        self.events();
    }

    App.prototype = {
        initParams: function (options) {
            var self = this;
            self.adaptation = options.adaptation;
            self.privateId = options.privateId;
            self.messageObj = options.getData;
            self.preUrl = options.url_prefix;
        },
        initDom: function () {
            var self = this;
            dynamicLoading.css(self.preUrl + 'css/formTableWord.css');
            self.appendChildDom();
        },
        events: function () {
            var self = this;
            // 监听是否数据刷新
            self.adaptation.ObserverEvent.listen('Event' + self.privateId, function () {
                self.messageObj = self.adaptation.childrenGetData(self.privateId);
                self.appendChildDom();
            });
        },
        appendChildDom: function () {
            var self = this;
            var domStructure = '<section class="customButton_box_content">' +
                '<div class="customButton_class_box ' + self.privateId + '" title="' + self.messageObj.display.escapeHTML() + '">' + self.messageObj.display.escapeHTML() + '</div>' +
                '</section>';
            document.querySelector('#' + self.privateId).innerHTML = domStructure;
            var jumpFun = function () {
                csdk.util.openMask()
                //上传模板控件名称
                var mbName = "表单转word模板"
                //获取回写控件
                var hxName = "套红附件"
                var hxFieldName = "";

                //是否上传了表单转word的模板
                var isUpWordMb = false;
                var subData = csdk.core.getFormData()
                //获取主表名称
                var filedInfoData = subData.metadata.tableInfo.formmain.tableName;
                //获取主表数据
                var masterTable = subData.formmains[filedInfoData];
                var masterTableList = [];
                for (const key of Object.keys(masterTable)) {
                    if (key.indexOf('field') !== -1) {
                        if(masterTable[key].display === undefined){
                            continue
                        }
                        if (masterTable[key].display === mbName) {
                            if (masterTable[key].value.length !== 0) {
                                isUpWordMb = true
                            }
                        }
                        if (masterTable[key].display === hxName) {
                            hxFieldName = key
                            continue
                        }
                        var value = "";
                        if (masterTable[key].type === 'attachment' || masterTable[key].type === 'image') {
                            var attList = masterTable[key].attachmentInfo.attachmentInfos
                            for (var j = 0; j < attList.length; j++) {
                                value += attList[j].fileUrl + ","
                            }
                        } else {
                            value = masterTable[key].value
                        }

                        var map = {};
                        map.value = value
                        map.display = masterTable[key].display
                        map.fieldName = key
                        map.fieldType = masterTable[key].type
                        masterTableList.push(map)
                    }
                }
                if (!isUpWordMb) {
                    csdk.util.alert('表单转word模板未上传！')
                    return
                }
                //获取明细表数据
                var fommsonTableData = subData.formsons
                var subAllDataList = [];
                for (const key of Object.keys(fommsonTableData)) {
                    var fommsonData = fommsonTableData[key]
                    var subDataList = [];
                    for (var i = 0; i < fommsonData.records.length; i++) {
                        var subRowDataList = [];
                        if (fommsonData.records[i] !== null) {
                            var subRowData = fommsonData.records[i].lists
                            for (const key of Object.keys(subRowData)) {
                                var value = "";
                                if (subRowData[key].type === 'attachment' || subRowData[key].type === 'image') {
                                    var attList = subRowData[key].attachmentInfo.attachmentInfos
                                    for (var j = 0; j < attList.length; j++) {
                                        value += attList[j].fileUrl + ","
                                    }
                                } else {
                                    value = subRowData[key].value
                                }
                                if(subRowData[key].display === undefined){
                                    continue
                                }
                                var map = {};
                                map.value = value
                                map.display = subRowData[key].display
                                map.fieldName = key
                                map.fieldType = subRowData[key].type
                                subRowDataList.push(map)
                            }
                            subDataList.push(subRowDataList)
                        }
                    }

                    var fommsonMap = {};
                    fommsonMap.tableDisplay = fommsonData.display
                    fommsonMap.tableName = fommsonData.tableName
                    fommsonMap.dataList = subDataList
                    subAllDataList.push(fommsonMap)
                }


                //组装参数信息
                var params = {'mbName': mbName, 'masterData': masterTableList, 'subDataList': subAllDataList};
                //调用后端接口
                $.ajax({
                    url: "/seeyon/rest/jssdk/formTable/word",
                    data: JSON.stringify(params),
                    type: "POST",
                    contentType: "application/json;charset=UTF-8",
                    error: function (data) {

                    },
                    success: function (data) {
                        if (data.status === '1') {
                            //回写表单数据
                            var formData = [{
                                tableName: filedInfoData,
                                tableCategory: 'formmain',
                                handlerMode: 'add',
                                fieldName: hxFieldName,

                                addAttchmentData: data.data,
                                deleteAttachmentData: []
                            }]
                            window.thirdPartyFormAPI.backfillFormAttachment(formData);
                            csdk.util.closeMask()
                            csdk.util.alert('调用后端接口成功！！！！')
                        } else {
                            csdk.util.closeMask()
                            csdk.util.alert(data.msg)
                        }
                    }
                });
            };
            document.querySelector('.' + self.privateId).removeEventListener('click', jumpFun);
            document.querySelector('.' + self.privateId).addEventListener('click', jumpFun);
            //渲染隐藏权限
            if (self.messageObj.auth === 'hide') {
                document.querySelector('#' + self.privateId).innerHTML = '<div class="cap4-text__browse" style="line-height: 1.8; color: rgb(0, 0, 0) !important;">***</div>';
            }
        },
        dealCdtMapping: function (opt) {
            $.ajax({
                url: '/seeyon/rest/cap4/formquerybtn/dealCdtMapping?formId=' + opt.formId + '&fieldName=' + opt.fieldName + '&formDataId=' + opt.formDataId + '&formSubDataId=' + opt.formSubDataId + '&designId=' + opt.designId,
                success: function (data) {
                    if (opt.callback && typeof opt.callback === 'function')
                        opt.callback.apply();
                },
                error: function (e) {
                    if (e.message) {
                        top.$.error(e.message);
                    } else {
                        top.$.error('处理筛查条件出错...');
                    }
                }
            });
        }
    };

    var dynamicLoading = {
        css: function (path) {
            if (!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
            link.href = path;
            link.rel = 'stylesheet';
            link.type = 'text/css';
            head.appendChild(link);
        },
        js: function (path) {
            if (!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.src = path;
            script.type = 'text/javascript';
            head.appendChild(script);
        }
    }

    return App;
});
